package com.weiyuwqj.api.common;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;


/**
 * Created by huzj on 2016/8/16.
 */
public class HtmlTranslator {

    public static void html2pdf(String htmlFileName, String padfFileName) throws Exception {

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                new FileOutputStream(padfFileName));
        pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
        document.open();

        // html文件
        InputStreamReader isr = new InputStreamReader(new FileInputStream(
                htmlFileName), "UTF-8");
        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, isr);
        document.close();
    }

    public static void html2pdf(MultipartFile htmlFile, String padfFileName) throws Exception {
        Document document = new Document();
        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                new FileOutputStream(padfFileName));
        pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
        document.open();

        // html文件
        InputStreamReader isr = new InputStreamReader(htmlFile.getInputStream(), "UTF-8");
        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, isr);
        document.close();
    }

    public static void string2pdf(String str, String padfFileName) throws Exception {
        Document document = new Document();
        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                new FileOutputStream(padfFileName));
        pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
        document.open();
        // html文件
        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(str.getBytes("UTF-8")), "UTF-8");
        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, isr);
        document.close();
    }




}
